package com.appcloner.data.repository

import com.appcloner.data.model.CardVerificationRequest
import com.appcloner.data.model.CardVerificationResponse
import com.appcloner.data.local.datastore.AppPreferences
import com.appcloner.network.ApiService
import javax.inject.Inject

class CardRepository @Inject constructor(
    private val apiService: ApiService,
    private val appPreferences: AppPreferences
) {
    
    suspend fun verifyCard(cardKey: String): Result<CardVerificationResponse> {
        return try {
            val deviceId = appPreferences.getDeviceId()
            val request = CardVerificationRequest(cardKey, deviceId)
            val response = apiService.verifyCard(request)
            
            if (response.isValid) {
                appPreferences.saveCardInfo(cardKey, response.expiresAt, response.permissionLevel)
            }
            
            Result.success(response)
        } catch (e: Exception) {
            // 离线验证逻辑
            val offlineResult = verifyOffline(cardKey)
            if (offlineResult != null) {
                Result.success(offlineResult)
            } else {
                Result.failure(e)
            }
        }
    }
    
    private suspend fun verifyOffline(cardKey: String): CardVerificationResponse? {
        val savedCardKey = appPreferences.getSavedCardKey()
        val expiresAt = appPreferences.getCardExpiresAt()
        val permissionLevel = appPreferences.getCardPermissionLevel()
        
        return if (cardKey == savedCardKey && System.currentTimeMillis() < expiresAt) {
            CardVerificationResponse(
                isValid = true,
                expiresAt = expiresAt,
                permissionLevel = permissionLevel,
                message = "离线验证成功"
            )
        } else {
            null
        }
    }
    
    suspend fun isCardValid(): Boolean {
        val expiresAt = appPreferences.getCardExpiresAt()
        return System.currentTimeMillis() < expiresAt
    }
}
